<template>
  <forms ref="forms" :config="config" @submit:forms="onsubmit" :btns="btns">
    <template v-slot:message_param="{row}">

      <div class="el-form-item" v-for="(label,k) in row.param_config">
        <label class="el-form-item__label" style="width: 8em;">{{label}}</label>
        <div class="el-form-item__content">
          <input type="hidden" :name="row.name+'['+k+']'" :value="row.value[k]">
          <div class="flex" style="width: 100%;">
            <text_one class="max" v-model:value="row.value[k]" computed="1"></text_one>
          </div>
        </div>
      </div>
    </template>


  </forms>
</template>

<script>
import text_one from "@/components/auto_import/UnifyParam/text_one.vue";
import s94Mjs from "s94-js";
import {ajax} from "@/js/api_tool.js";
import {iframe} from "@/js/tool.js";
import {S94Model} from "@/js/S94Model.js";
import {_config, decode_config, s94_event} from "@/js/s94_tool.js";
export default {
  components: {text_one},
  props: ['__iframe'],
  data(){
    let id = this.$get('id'), btns = undefined;

    let model_name_config = decode_config(_config('model_map'), {content_key:'label', value_key:'name'});
    let forms_config = {
      title: {name:'title', label:'标题',type:'text_one'},
      limit_model_name: {name:'limit_model_name', label:'模型限定', type:'select_more', config:model_name_config, tips:'多个逗号分割'},
      bind_event_name: {name:'bind_event_name', label:'绑定事件', type:'text_one', tips:'多个逗号分割'},
      need_log: {name:'need_log', label:'是否记录', type:'radio_switch',tips:'',value:0},
      async: {name:'async', label:'异步执行', type:'radio_switch',tips:'是否放在异步队列中执行',value:0, is_info:false},
      throw: {label:'抛出异常',name:'throw',type:'radio_switch',tips:'如果抛出移除，执行方法出错时，会中断程序',value:0},
      retry_max: {name:'retry_max', label:'最多重试', type:'text_one',tips:'执行失败重新尝试的次数',value:0},
      function: {label:'执行方法',name:'function',type:'select_one',config:[],tips:''},
    }

    let function_map={}, field_map={};
    ajax({url:'/admin/execute/config_map?field=1',cache:true,async:false},function (res){
      function_map = res.data.function_map;
      field_map = res.data.field_map;

      forms_config.function.config = [];
      Object.keys(function_map).forEach((k)=>{
        forms_config.function.config.push({content:function_map[k].title, value:k});
      })

      Object.keys(field_map).forEach((k)=>{
        forms_config[k] = field_map[k];
        forms_config[k].remove = true;
      })
      return false;
    })

    if (id){
      forms_config.create_time = {label:'创建时间',name:'create_time',tips:''};
    }
    if (this.$get('is_info')){
      s94Mjs.each(forms_config, function (row){ row.is_info = true; });
      btns = [];
    }
    return {
      id: id,
      btns: btns,
      config: forms_config,
      function_map: function_map,
      field_map: field_map,

    }
  },
  methods: {
    onsubmit(formData){
      let url = this.id ? `/admin/execute/edit?id=`+this.id : '/admin/execute/add';
      ajax({url:url, method:'POST', data:formData}, (res)=>{
        if (this.__iframe){
          s94_event(`execute/${this.id?'edit':'add'}`, res);
          // iframe.exe('execute/index', '$refs.list_url.list');
          iframe.hide('execute/edit');
          if (!this.id) this.$refs['forms'].init();
        }else {
          this.$router.push('index');
        }
      }, (res)=>{
        if (res.errors) this.$refs['forms'].errors = res.errors;
      })
    },
    change_function_after(){
      let func = this.config.function.value;
      let param_key = this.function_map[func]?.param_key || [];
      Object.keys(this.field_map).forEach((k)=>{
        this.config[k].remove = !~param_key.indexOf(k);
      })
    },
    change_message_id(id, config_name){
      let app = this;
      let old_v = app.config[config_name].value || {};

      ajax('/admin/message_template/info?id='+id, function(res){
        let param_map = JSON.parse(res.data.param);
        app.config[config_name].value = {};
        Object.keys(param_map).forEach((k)=>{
          app.config[config_name].value[k] = old_v[k] || '';
        })
        app.config[config_name].param_config = param_map;
        return false;
      })
    },
  },
  watch:{
    'config.function.value'(func){
      let app = this;
      this.change_function_after();
    },
    'config.async.value'(v){
      this.config.throw.remove = v*1 === 1; //异步执行隐藏抛出异常选项
    },
    'config.p30.value'(v, oldV){
      if (v && v != oldV) this.change_message_id(v, "p31");
    },
  },
  mounted() {
    let app = this;
    if (!this.__iframe) window['app'] = this;
    if (this.id) {
      ajax({url:'/admin/execute/info?id='+this.id, cache:true}, (res)=>{
        let param = JSON.parse(res.data.param);
        delete res.data.param;
        app.$refs['forms'].init(res.data);
        setTimeout(function(){
          Object.keys(app.field_map).forEach((k)=>{
            if (app.config[k].remove) return;
            let ms = app.config[k].name.match(/param\[(\w+)\]/);
            let param_name = ms ? ms[1] : '';
            if (param_name){
              app.config[k].value = param[param_name];
            }
          })
        },10)
        return false;
      }, ()=>{
        if (this.__iframe){
          iframe.remove('execute/edit');
        }else {
          this.$router.push('index');
        }
      })
    }

    //其他初始化操作
  }
}
</script>
